package com.qf.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.service.impl.PayServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@Component
public class AlipayUtils {

    @Value("${alipay.serverURL}")
    private String serverUrl;
    @Value("${alipay.appId}")
    private String appId;
    @Value("${alipay.privateKey}")
    private String privateKey;
    @Value("${alipay.format}")
    private String format;
    @Value("${alipay.charset}")
    private String charset;
    @Value("${alipay.publicKey}")
    private String publicKey;
    @Value("${alipay.signType}")
    private String signType;
    @Value("${alipay.returnUrl}")
    private String returnUrl;
    @Value("${alipay.notifyUrl}")
    private String notifyUrl;
    @Value("${alipay.alipayPublickey}")
    private String alipayPublickey;

    private static Logger logger = LoggerFactory.getLogger(AlipayUtils.class);
    public String pay(String orderid,Double money){
        //1.声明调用的客户端
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, publicKey, signType);
        //2.电脑网站支付的request
        AlipayTradePagePayRequest alipayRequest =  new AlipayTradePagePayRequest(); //创建API对应的request
        //3.同步通知
        alipayRequest.setReturnUrl( returnUrl);
        //4.异步通知
        alipayRequest.setNotifyUrl( notifyUrl); //在公共参数中设置回跳和通知地址
        //out_trade_no ：订单号：注意 每个订单号都不能重复
        //product_code 商品的编码 FAST_INSTANT_TRADE_PAY
        //total_amount 价格 字符串
        //subject 主题
        //body 主体
        Map map = new HashMap<>();
        map.put("out_trade_no", orderid);
        map.put("product_code", "FAST_INSTANT_TRADE_PAY");
        map.put("product_code", "FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",money);
        map.put("subject", "千锋商品购买课程！");
        map.put("body", "课程购买");
        String s = JSONObject.toJSONString(map);
        alipayRequest.setBizContent(s); //填充业务参数
        String form= "" ;
        try  {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }

    public Map notifyUrl(HttpServletRequest request){
        Map<String, String> stringStringMap = convertRequestParamsToMap(request);
        //验签操作
        Map returnMap = new HashMap();
        boolean signVerified=false;
        try {

            signVerified= AlipaySignature.rsaCheckV1(stringStringMap, alipayPublickey, charset, signType); //调用SDK验证签名
            logger.error("验签是否成功：{}"+signVerified);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.error("验签异常：{}"+e.getErrMsg());
        }
        returnMap.put("signVerified",signVerified);
        returnMap.put("payResult",stringStringMap);
        return returnMap;
    }

    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }

}
